package com.bourne.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.bourne.interceptor.AuthInterceptor;
import com.bourne.model.LoginUser;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @description 自动填充
 * @program base_farme
 * @author: bourne
 * @create 2021-11-14 10:44:58
 **/
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override public void insertFill(MetaObject metaObject) {
        // 插入时自动填充
        LoginUser loginUser = AuthInterceptor.threadLocal.get();
        if (loginUser != null) {
            strictFillStrategy(metaObject, "createUser", loginUser::getId);
            strictFillStrategy(metaObject, "updateUser", loginUser::getId);
        }
        // 注意第二个参数要填写实体类中的字段名称，而不是表的列名称
        strictFillStrategy(metaObject, "createTime", LocalDateTime::now);
    }

    @Override public void updateFill(MetaObject metaObject) {
        // 更新时自动填充
        strictFillStrategy(metaObject, "updateTime", LocalDateTime::now);
    }
}
